import tkinter as tk
from tkinter import Entry, ttk
from tkinter import filedialog
import constant.param_config as config


class ConfigView:

    def __init__(self, window, root):
        self.window = window
        self.validateCmd = root.register(self.on_validate)

        self.width = root.winfo_reqwidth()
        self.height = root.winfo_reqheight()
        self.configFrame = tk.Frame(root, width=self.width, height=self.height)
        self.configFrame.configure(background="#121212")
        self.configFrame.grid(row=0, column=1, sticky="nsew")
        self.createView()

    def createView(self):

        def saveClick():
            config.changeMt5Account(self.accountBox.get())
            config.changeMt5Password(self.pwdVar.get())
            config.changeMt5Server(self.serverBox.get())
            config.changeMt5Path(self.pathVar.get())
            config.initConfig(write=True)

        title = tk.Label(self.configFrame,
                         bg="#121212",
                         text="配置中心",
                         font=("Helvetica", 12, "bold"),
                         foreground="#FFFFFF")
        title.place(x=self.width / 2 - 50, y=10)

        saveBu = tk.Button(self.configFrame, text="保存修改", command=saveClick)
        saveBu.pack(side=tk.RIGHT, anchor=tk.N, padx=10, pady=10)

        self.scrollFrame = tk.Frame(self.configFrame,
                                    width=self.width,
                                    height=self.height - 50)
        self.scrollFrame.configure(background="#121212")
        self.scrollFrame.place(y=50, x=0)
        self.createScrollView()

    def createScrollView(self):
        self.scrollFrame.columnconfigure(0, weight=1)
        self.scrollFrame.rowconfigure(0, weight=1)

        self.scrollWidth = self.scrollFrame.winfo_reqwidth()
        self.scrollHeight = self.scrollFrame.winfo_reqheight()

        self.canvas = tk.Canvas(self.scrollFrame,
                                width=self.scrollWidth - 25,
                                height=self.scrollHeight,
                                highlightthickness=0,
                                background="#121212")
        self.canvas.grid(row=0, column=0, sticky="nsew")

        scrollbar = ttk.Scrollbar(self.scrollFrame,
                                  orient=tk.VERTICAL,
                                  command=self.canvas.yview)
        scrollbar.grid(row=0, column=1, sticky="ns")

        self.canvas.configure(yscrollcommand=scrollbar.set)

        self.scrollable_frame = tk.Frame(self.canvas,
                                         padx=20,
                                         background="#121212")
        self.canvas.create_window((0, 0),
                                  window=self.scrollable_frame,
                                  anchor=tk.NW,
                                  width=self.scrollWidth - 30)

        self.canvas.bind("<Configure>", self.on_canvas_configure)
        self.canvas.bind("<MouseWheel>", self.on_mousewheel)

        self.loginConfigView()
        self.tradeConfigView()
        self.spiderConfigView()
        self.indicatorConfigView()
        self.othersConfigView()

    def on_canvas_configure(self, event):
        self.scrollFrame.update_idletasks()
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def on_validate(self, P):
        # 验证函数，检查输入是否为数字
        try:
            if P == "":
                return True
            float(P)
            return True
        except ValueError:
            return False

    def listRemoveItem(self, listValue):
        """
        从后往前去除list中相同的元素
        """
        seen = []
        for item in listValue:
            if item not in seen:
                seen.append(item)
        return seen

    def on_mousewheel(self, event):
        """
        通过鼠标滚轮事件滑动滚动条
        """
        self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")

    def loginConfigView(self):
        """
        登录配置
        """
        loginLable = tk.Label(self.scrollable_frame,
                              background="#121212",
                              text="登录配置:",
                              pady=5,
                              padx=0,
                              font=("NORMAL", 11),
                              foreground="#FFFFFF")
        loginLable.pack(anchor=tk.W)

        accountLable = tk.Label(self.scrollable_frame,
                                background="#121212",
                                text="MT5账号:",
                                pady=5,
                                padx=0,
                                width=10,
                                anchor="e",
                                justify="right",
                                font=("NORMAL", 10),
                                foreground="#FFFFFF")
        accountLable.pack(anchor=tk.W)

        def accountSelect(event):
            value = int(accountVar.get())
            for item in config.getHisMap():
                if item["mt5Account"] == value:
                    self.pwdVar.set(item["mt5Pwd"])
                    self.serverBox['values'] = item["mt5Server"]
                    self.pathVar.set(item["mt5Path"])

        accountVar = tk.StringVar()
        self.accountBox = ttk.Combobox(self.scrollable_frame,
                                       validate="key",
                                       textvariable=accountVar,
                                       validatecommand=(self.validateCmd,
                                                        '%P'))
        accountList = [config.getMt5Account()]
        accountList.extend(item["mt5Account"] for item in config.getHisMap())
        arrList = self.listRemoveItem(accountList)
        self.accountBox['values'] = arrList

        self.accountBox.place(x=80, y=30, width=250)
        self.accountBox.current(0)
        self.accountBox.bind("<<ComboboxSelected>>", accountSelect)

        pwdLable = tk.Label(self.scrollable_frame,
                            background="#121212",
                            text="登录密码:",
                            pady=5,
                            padx=0,
                            width=10,
                            anchor="e",
                            justify="right",
                            font=("NORMAL", 10),
                            foreground="#FFFFFF")
        pwdLable.pack(anchor=tk.W)

        self.pwdVar = tk.StringVar()
        pwdEntry = Entry(
            self.scrollable_frame,
            bd=2,
            width=10,
            font="Roboto 11",
            textvariable=self.pwdVar,
        )
        self.pwdVar.set(config.getMt5Password())
        pwdEntry.place(x=80, y=58, width=250)

        serverLable = tk.Label(self.scrollable_frame,
                               background="#121212",
                               text="服务器:",
                               pady=5,
                               padx=0,
                               width=10,
                               anchor="e",
                               justify="right",
                               font=("NORMAL", 10),
                               foreground="#FFFFFF")
        serverLable.pack(anchor=tk.W)

        self.serverBox = ttk.Combobox(self.scrollable_frame)
        serverList = [config.getMt5Server()]
        serverList.extend(item["mt5Server"] for item in config.getHisMap())
        servers = self.listRemoveItem(serverList)
        self.serverBox['values'] = servers
        self.serverBox.place(x=80, y=86, width=250)
        self.serverBox.current(0)

        pathLable = tk.Label(self.scrollable_frame,
                             background="#121212",
                             text="MT5路径:",
                             pady=5,
                             padx=0,
                             width=10,
                             anchor="e",
                             justify="right",
                             font=("NORMAL", 10),
                             foreground="#FFFFFF")
        pathLable.pack(anchor=tk.W)

        self.pathVar = tk.StringVar()
        pathEntry = Entry(
            self.scrollable_frame,
            bd=2,
            width=10,
            font="Roboto 11",
            textvariable=self.pathVar,
        )
        self.pathVar.set(config.getMt5Path())
        pathEntry.place(x=80, y=114, width=250)

        pathBu = tk.Button(self.scrollable_frame,
                           text="选择",
                           command=self.fileSelect,
                           font=("NORMAL", 8))
        pathBu.place(x=335, y=114)

    def fileSelect(self):
        """
        文件选择
        """
        file_path = filedialog.askopenfilename(title="Select a file")
        if file_path:
            self.pathVar.set(file_path)

    def tradeConfigView(self):
        """
        交易配置
        """
        space = tk.Label(
            self.scrollable_frame,
            background="#121212",
            pady=3,
        )
        space.pack()

        tradeLable = tk.Label(self.scrollable_frame,
                              background="#121212",
                              text="交易配置:",
                              pady=5,
                              font=("NORMAL", 11),
                              foreground="#FFFFFF")
        tradeLable.pack(anchor=tk.W)

    def spiderConfigView(self):
        """
        爬虫配置
        """
        spiderLable = tk.Label(self.scrollable_frame,
                               background="#121212",
                               text="爬虫配置:",
                               pady=5,
                               font=("NORMAL", 11),
                               foreground="#FFFFFF")
        spiderLable.pack(anchor=tk.W)

    def indicatorConfigView(self):
        """
        指标配置
        """
        indicatorLable = tk.Label(self.scrollable_frame,
                                  background="#121212",
                                  text="指标配置:",
                                  pady=5,
                                  font=("NORMAL", 11),
                                  foreground="#FFFFFF")
        indicatorLable.pack(anchor=tk.W)

    def othersConfigView(self):
        """
        其他配置
        """
        othersLable = tk.Label(self.scrollable_frame,
                               background="#121212",
                               text="其他配置:",
                               pady=5,
                               font=("NORMAL", 11),
                               foreground="#FFFFFF")
        othersLable.pack(anchor=tk.W)
